#include <sys_head.h>

int main(int argc, char const *argv[])
{
    //判断命令行参数
    if (argc < 2)
    {
        printf("参数错误:%s ip port\n",argv[0]);
        return -1;
    }

    // 给定默认ip

    char ip_str[128];

    if ( 3 != argc )
    {
        
        strcpy( ip_str , "192.168.91.182");
    }
    else{
        
        strcpy( ip_str , argv[2]);
    }

    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);

    // 填充服务器网络信息结构体
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(atoi(argv[1]));
    server_addr.sin_addr.s_addr = inet_addr(ip_str);

    socklen_t len = sizeof(server_addr);

    // 绑定
    bind(sockfd, (struct sockaddr *)&server_addr, len);

    // 收发数据
    struct sockaddr_in client_addr;
    socklen_t client_len = sizeof(client_addr);
    char buf[1024];
    while (1)
    {
        memset(buf, 0, sizeof(buf));
        // 接收数据
        recvfrom(sockfd,buf, sizeof(buf),0,(struct sockaddr *)&client_addr,&client_len);
        printf("接收到的信息为:%s\n",buf);
        // 发送数据
        ssize_t bytes = sendto(sockfd,buf,sizeof(buf),0,(struct sockaddr *)&client_addr,client_len);
        if (strcmp(bytes,"quit") == 0)
        {
            break;
        }
    }
    
    return 0;
}
